package com.gdatacloud.ai;

import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class FreemarkerToDoc {
    public static void main2(String[] args) {
        Configuration configuration = new Configuration();
        try {
            configuration.setDefaultEncoding("utf-8");
            configuration.setDirectoryForTemplateLoading(new File("D:\\data1\\hanwei\\执法文书模板"));
            Template template = configuration.getTemplate("1xcjc.ftl");

            Map<String, Object> data = new HashMap<>();
            data.put("entBusinessinfo", "123");
            data.put("startTimeMap", "2024");
            data.put("lawCheckrecord", "1、安全措施不到位\n" +
                    "2、安全措施不到位\n" +
                    "3、安全措施不到位\n" +
                    "4、安全措施不到位\n" +
                    "5、安全措施不到位\n" +
                    "6、安全措施不到位");

            String outputFile = "output.docx";

            try (Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"))) {
                template.process(data, out);
                System.out.println("Template processed successfully!");
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("I/O error occurred while processing the template or writing the output file.");
            } catch (TemplateException e) {
                e.printStackTrace();
                System.err.println("Error while processing the FreeMarker template.");
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Error setting the FreeMarker configuration or loading the template.");
        }


    }

    public static void convertWordToPdf(String docxFileName, String pdfFileName) {
        try(InputStream inputStream = new FileInputStream(docxFileName);
            OutputStream outputStream = new FileOutputStream(pdfFileName)) {
            XWPFDocument document = new XWPFDocument(inputStream);
            PdfOptions options = PdfOptions.create();
            // Convert .docx file to .pdf file
            PdfConverter.getInstance().convert(document, outputStream, options);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        convertWordToPdf("output.docx", "output.pdf");
    }
}
